function Items()
{
	var labbyContainer = $("#labby");
	var afterSaveItem = function(obj, pu)
	{
		
		alert("El item fue guardado con éxito");
		pu.theForm.append($("<input type='hidden' name='pk' value='"+obj.pk+"' />"));
		var fileInput = $(pu.theForm).find("input[type='file']");

		if(fileInput.length > 0)
		{
			$.ajax({
			url: "items/savePic", // Url to which the request is send
			type: "POST",             // Type of request to be send, called as method
			data: new FormData(pu.theForm[0]), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
			contentType: false,       // The content type used when sending data to the server.
			cache: false,             // To unable request pages to be cached
			processData:false,        // To send DOMDocument or non processed data file it is set to false
			success: function(response)   // A function to be called if request succeeds
			{
				var responseObject = JSON.parse(response);
				if(util.handleResponseError(responseObject))
				{
					return;
				}
				util.refresh("/items");
			}
			});
		}
		else
		{
			util.refresh("/items");
		}
		
		
	};
	this.initInfoPopup = function(response)
	{
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		//Close function
		$(".more-info-popup .close-btn").on("click", function(){
			$(html).remove();
		});
	};
	this.saveItem = function(item, afterSaveFx)
	{
		var filters = util.filters();
		util.appendFilter({val: item.reference, name: "Referencia", filters: [filters.MAX_SIZE], extraval: 250});
		util.appendFilter({val: item.name, name: "Nombre", filters: [filters.MAX_SIZE], extraval: 250});
		util.appendFilter({val: item.located_at_fk, name: "'Localizado en'", filters: [filters.NUMBERS_ONLY], message: "El campo 'Localizado en' contiene información inválida.", extraval: 250});
		util.appendFilter({val: item.price, name: "Precio", filters: [filters.DECIMAL], extraval: 250});
		util.appendFilter({val: item.amount, name: "Cantidad", filters: [filters.DECIMAL], extraval: 250});

		var onFilterFx = function()
		{
			var params = {
				item: item
			};
			var afterSave = function(response)
			{
				response = JSON.parse(response);
				if(util.handleResponseError(response))
				{
					return;
				}
				if(afterSaveFx)
				{
					afterSaveFx(response);
				}
			};
			$.post("items/saveItem", params, afterSave);
		};

		util.runFilters(onFilterFx);

	};
	this.deleteItem = function(item, afterDeleteFx)
	{
			
		var params = {
			item: item
		};
		var afterDelete = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			if(afterDeleteFx)
			{
				afterDeleteFx();
			}
		};
		$.post("items/deleteItem", params, afterDelete);
	};
	this.initEditPopup = function(response)
	{
		var thisObj = this;
		response.item = JSON.parse(response.item);
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		response.item.reference = $("#reference").val();
		response.item.name = $("#name").val();
		response.item.located_at_fk = $("#located_at_fk").val();
		response.item.price = $("#price").val();
		response.item.amount = $("#amount").val();

		var addOnChangeEvent = function(el, attr)
		{
			$(el).on("change", function(){
				response.item[attr] = $(this).val().trim();
			});
			$(el).removeAttr("id");
		};
		//Form elements
		addOnChangeEvent($("#reference"),"reference");
		addOnChangeEvent($("#name"),"name");
		addOnChangeEvent($("#located_at_fk"),"located_at_fk");
		addOnChangeEvent($("#price"),"price");
		addOnChangeEvent($("#amount"),"amount");
		//Close function
		$(".edit-popup .cancel-btn").on("click", function(){
			if(confirm("¿Está seguro?"))
			$(html).remove();
		});

		$(".edit-popup .save-btn").on("click", function(){
			thisObj.saveItem(response.item, function(obj){afterSaveItem(obj, pu);});
		});
		var pu = util.getPictureUploader($(".image-uploader .image-preview"), $(".image-uploader .upload-btn"));
	};
	this.initCreatePopup = function(response)
	{
		var thisObj = this;
		response.item = JSON.parse(response.item);
		var html = $.parseHTML(response.html);
		labbyContainer.append(html);
		var addOnChangeEvent = function(el, attr)
		{
			
			$(el).on("change", function(){
				response.item[attr] = $(this).val();
			});
			$(el).removeAttr("id");
		};
		//Form elements
		addOnChangeEvent($("#reference"),"reference");
		addOnChangeEvent($("#name"),"name");
		addOnChangeEvent($("#located_at_fk"),"located_at_fk");
		addOnChangeEvent($("#price"),"price");
		addOnChangeEvent($("#amount"),"amount");

		$(".create-popup .save-btn").on("click", function(){
			thisObj.saveItem(response.item, function(obj){afterSaveItem(obj, pu);});
		});
		//Close function
		$(".create-popup .cancel-btn").on("click", function(){
			if(confirm("¿Está seguro?"))
			$(html).remove();
		});
		
		var pu = util.getPictureUploader($(".image-uploader .image-preview"), $(".image-uploader .upload-btn"));
	};
	this.showMoreInfo = function(id)
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			
			var responseObject = JSON.parse(response);
			if(util.handleResponseError(responseObject))
			{
				return;
			}
			thisObj.initInfoPopup(responseObject);
		};
		var params = 
		{
			pk: id
		}
		$.post("items/getItemInfo", params, afterLoad);
	};
	this.showEditItem = function(id)
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			
			var responseObject = JSON.parse(response);
			if(util.handleResponseError(responseObject))
			{
				return;
			}
			
			thisObj.initEditPopup(responseObject);
		};
		var params = 
		{
			pk: id
		}
		$.post("items/getItemEdit", params, afterLoad);
	};
	this.showDeleteItem = function(id)
	{	
		if(confirm("¿Realmente quieres borrar este item?"))
		{
			var afterDeleteFx = function()
			{
				alert("El item fue eliminado con éxito.");
				util.refresh("/items");
			};
			this.deleteItem(id, afterDeleteFx);
		}
	};
	this.showCreateItem = function()
	{
		var thisObj = this;
		var afterLoad = function(response)
		{
			response = JSON.parse(response);
			if(util.handleResponseError(response))
			{
				return;
			}
			thisObj.initCreatePopup(response);
		};
		$.post('items/createItem', {}, afterLoad);
	};
	this.initItemFilters = function()
	{
		var referenceEl = $(".items-filter .reference input");
		var nameEl = $(".items-filter .name input");
		var priceFromEl = $(".items-filter .price-from input");
		var priceToEl = $(".items-filter .price-to input");

		var reference = $(referenceEl).val();
		var name = $(nameEl).val();
		var priceFrom = $(priceFromEl).val();
		var priceTo = $(priceToEl).val();

		referenceEl.on("change", function(){
			reference = $(this).val();
		});

		nameEl.on("change", function(){
			name = $(this).val();
		});

		priceFromEl.on("change", function(){
			priceFrom = $(this).val();
		});

		priceToEl.on("change", function(){
			priceTo = $(this).val();
		});

		$(".items-filter .controls a").on("click", function(){
			var filters = util.filters();
			
			util.appendFilter({val: reference, name: "Referencia", filters: [filters.MAX_SIZE], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: name, name: "Nombre", filters: [filters.MAX_SIZE], extraval: 250, canBeEmpty: true});
			util.appendFilter({val: priceFrom, name: "'Precio desde'", filters: [filters.DECIMAL], canBeEmpty: true});
			util.appendFilter({val: priceTo, name: "'Precio hasta'", filters: [filters.DECIMAL], canBeEmpty: true});
			var afterFiltersFx = function()
			{
				var url = "items";
				url = reference === "" ? url : util.addUrlParam(url, "reference", reference);
				url = name === "" ? url : util.addUrlParam(url, "name", name);
				url = priceFrom === "" ? url : util.addUrlParam(url, "priceFrom", priceFrom);
				url = priceTo === "" ? url : util.addUrlParam(url, "priceTo", priceTo);
				util.goTo(url);
			};
			util.runFilters(afterFiltersFx);
		});
	};
	this.restoreItem = function(id)
	{
		if(confirm("¿Seguro que desea restaurar este item?"))
		{
			var params = {
				id: id
			};
			var afterRestoreFx = function(response)
			{
				response = JSON.parse(response);
				if(util.handleResponseError(response))
				{
					return;
				}
				alert("El item fue restaurado con éxito.");
				util.refresh("/items");
			};
			$.post("items/restoreItem", params, afterRestoreFx);
		}
	};
	this.init = function()
	{
		var thisObj = this;
		$("#items-table tr").each(function()
		{
			var theTr = this;
			var id = $(theTr).attr("id");
			var moreBtn = $(theTr).find("a[class='btn more']");
			var editBtn = $(theTr).find("a[class='btn edit']");
			var deleteBtn = $(theTr).find("a[class='btn delete']");

			moreBtn.on("click", function()
			{
				
				thisObj.showMoreInfo(id);
			});
			editBtn.on("click", function()
			{
				thisObj.showEditItem(id);
			});
			deleteBtn.on("click", function()
			{
				thisObj.showDeleteItem(id);
			});
			$(theTr).removeAttr("id");
		});
		
		$("#items-trash-table tr").each(function()
		{
			var theTr = this;
			var id = $(theTr).attr("id");
			var moreBtn = $(theTr).find("a[class='btn more']");
			var restoreBtn = $(theTr).find("a[class='btn restore']");

			moreBtn.on("click", function()
			{
				thisObj.showMoreInfo(id);
			});
			restoreBtn.on("click", function()
			{
				thisObj.restoreItem(id);
			});
			$(theTr).removeAttr("id");
		});
		
		$(".item-options .create").on("click", function(){
			thisObj.showCreateItem();
		});
	};
	this.init();
	this.initItemFilters();
}

var itms = new Items();